package top.lzy.hive.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.lzy.hive.entity.Country;
import top.lzy.hive.entity.LoginRequest;
import top.lzy.hive.service.FileService;

import java.io.IOException;
import java.sql.ResultSet;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;

@CrossOrigin
@RestController
@RequestMapping("/hive")
public class HiveController {
    @Resource
    FileService fileService;
    @Resource
    JdbcTemplate jdbcTemplate;

    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空");
        }
        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".xlsx")) {
            return ResponseEntity.badRequest().body("文件格式不正确");
        }
        List<Country> countries = fileService.parseFile(file);
        return ResponseEntity.ok().body(countries);
    }

    @GetMapping("/query")
    public ResponseEntity<List<Country>> query() {

        List<Country> countries = fileService.getCountries();
        return ResponseEntity.ok().body(countries);
    }

    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody LoginRequest loginRequest) {
        String sql = "select * from users where username=? and password=?";
        List<LoginRequest> query = jdbcTemplate.query(sql, (ResultSet resultSet, int i) -> {
            LoginRequest loginRequest1 = new LoginRequest();
            loginRequest1.setUsername(resultSet.getString("username"));
            loginRequest1.setPassword(resultSet.getString("password"));
            return loginRequest1;
        }, loginRequest.getUsername(), loginRequest.getPassword());
        if (query.size() == 1) {
            return ResponseEntity.ok().body("登录成功");
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录失败");
    }
}
